﻿import logging
import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import os
from google.appengine.ext.webapp import template

import simplejson as json

class MainPage(webapp.RequestHandler):
	def get(self):
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			
			template_values = {
				'url': url,
				'url_linktext': url_linktext,
				'user': users.get_current_user(),
			}

			path = os.path.join(os.path.dirname(__file__), '../templates/main.html')
			self.response.out.write(template.render(path, template_values))
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			
			template_values = {
				'url': url,
				'url_linktext': url_linktext,
				'user': users.get_current_user(),	
			}
			
			path = os.path.join(os.path.dirname(__file__), '../templates/main_logged_out.html')
			self.response.out.write(template.render(path, template_values))	
			
		
	
class File(db.Model):
  author = db.UserProperty()
  title = db.StringProperty()
  content = db.TextProperty()
  date = db.DateTimeProperty(auto_now_add=True)	

class FileSave(webapp.RequestHandler):
	def post(self):
		file = File()
		
		user = users.get_current_user()
		if user is None:
			return

		file.author = users.get_current_user()
		file.title = self.request.get('title');
		file.content = self.request.get('content');
		file.put()
	
class FileLoad(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		if user is None:
			self.response.out.write("{}")
			return
		title = self.request.get('title')
		q = File.all()
		q.filter("title =", title)
		
		file = q.get()
		self.response.out.write(json.dumps({"content":file.content}))
		
class FileView(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		if user is None:
			self.response.out.write("{}")
			return
		title = self.request.get('title')
		q = File.all()
		q.filter("title =", title)
		
		file = q.get()
		if file is None:
			self.response.out.write("doesn't exist")
		else:
			self.response.out.write(file.content)
			
class Files(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		if user is None:
			self.response.out.write('[]')
			return
		
		node = self.request.get('node')
		if node != "/":
			self.response.out.write('[]')
			return 
		
		q = File.all()
		q.filter("author =", user)
		q.order("title")
		files = q.fetch(1000)
		
		result = []
		for file in files:
			result.append({
				"leaf": 0,
				"text": file.title,
				"cls": "file",
				"id": "/" + file.title,
				"leaf": "true"
			})
			
			
		
		self.response.out.write(json.dumps(result))

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/save.*', FileSave),
									  ('/load.*', FileLoad),
									  ('/files.*',Files),
									  ('/view.*',FileView)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()